//
//  changePastInfo.m
//  Gradekeeper0.2
//
//  Created by Ben Wu on 11/24/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ChangePastInfo.h"
#import "fileIO.h"
#import "ProfileDetailViewController.h"
#import "Profile.h"
#define LEGAL	@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
#define legal2  @"0123456789"
#define legal3  @"0123456789."


@implementation ChangePastInfo

- (void)viewDidLoad {
	//Create a cancel button that lets the user cancel profile creation
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" 
																	 style:UIBarButtonItemStyleBordered 
																	target:self 
																	action:@selector(cancelCreate:)]; 
	self.navigationItem.leftBarButtonItem = cancelButton; 
	[cancelButton release]; 
	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[cgpa release];
	[credits release];
	[semester release];
	[super dealloc];
}

- (void)cancelCreate:(id)sender {
	
	//If user confirms cancellation, current view will be popped and return to profile manager list (ProfileTableViewController)
	UIAlertView *alert = [[UIAlertView alloc] 
						  initWithTitle:@"Cancel Confirmation" 
						  message:@"Are you sure you would like to cancel editing?" 
						  delegate:self
						  cancelButtonTitle:@"Yes" 
						  otherButtonTitles:nil]; 
	[alert addButtonWithTitle:@"No"];
    [alert show];
	
	[alert release];
	
} //cancelCreate

- (IBAction) btnClickMe_Clicked: (id) sender{
	NSString *mycgpa = cgpa.text;
	NSString *mycredits = credits.text;
	NSString *mysem = semester.text;
	
	//Checks if username is at least 3 characters long, or if the profile already exists.
	//If a profile is created, the user will be alerted
	if ([mycgpa length] > 4 && [mycredits length] > 3 && [mysem length] > 11 ){
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Invalid inputs" 
							  message:@"Please Follow the Format\nCGPA : 1.23\nCredits Used : 110\nSemester : Summer 2008" 
							  delegate:self
							  cancelButtonTitle:nil
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		
	} /*else if ([self profileExist:myName]){
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Invalid Username" 
							  message:@"The name you have entered has already been taken. Please choose another name." 
							  delegate:self
							  cancelButtonTitle:nil
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		
	}*/
		else {
		[self writeToTextFile:self];
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Successed" 
							  message:@"Information updated" 
							  delegate:self
							  cancelButtonTitle:@"Ok" 
							  otherButtonTitles:nil]; 
		[alert show];
		[alert release];
	}
} //btnClickMe_Clicked


//If the alert is due to invalid username, do nothing
//Otherwise, the alert comes from cancellation request
//If cancellation is confirmed, pop to root view controller
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:@"Invalid Username"]){
	} else { 
		if (buttonIndex == 0) {
			[[self navigationController] popViewControllerAnimated:YES];
			
		}
    }
} //alertView

//Takes the username entered and addeds it to profileManager.txt
//and creates a textfile with the same name as the entered username.
-(IBAction) writeToTextFile:(id)sender{
	NSString *mycgpa = cgpa.text;
	NSString *mycredits = credits.text;
	NSString *mysem = semester.text;
	
	Profile *profile = [Profile sharedProfile];
	NSString *myname = [[NSString alloc] initWithFormat: @"%@", [profile getUserName]];

	[profile setCGPA:mycgpa];
	[profile setCreditsUsed:mycredits];
	[profile setSemester:mysem];
	
	[fileIO writeToFile: myname : mycgpa];	
	[fileIO appendToFile: myname : mycredits];
	[fileIO appendToFile: myname : mysem];
		
	
	
		
} //writeToTextFile


//Checks if a profile with the same username exists by comparing the entered username to names in profileManager.txt
- (BOOL) profileExist: (NSString *) desiredName{
	
	Profile *profile = [Profile sharedProfile];
	NSString *myname = [[NSString alloc] initWithFormat: @"%@", [profile getUserName]];
	
	
	NSString *tempList = nil;
	
	tempList = [[NSString alloc] initWithFormat:@"%@", [fileIO readFromFile:myname]];
	
	NSArray *tempArray = [tempList componentsSeparatedByString: @":"];
	for (int y = 1; y < [tempArray count]; y ++){
		
		if ([[tempArray objectAtIndex:y] caseInsensitiveCompare: desiredName] == NSOrderedSame){
			
			return YES;
		} 			
	};	
	
	return NO;
} //profileExist


// allow only legal input (less than 20 chars, numbers/letters)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	NSInteger insertDelta = string.length - range.length;
	
	if (textField.text.length + insertDelta > 20)
	{
		return NO; // the new string would be longer than MAX_LENGTH
	}
	else {
		NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];
		NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
		
		return [string isEqualToString:filtered];
	}
} //textField

//Hides the keyboard after finishing text input (clicking done)
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	//if (textField == cgpa) {
		[cgpa resignFirstResponder];
	//}
	//else if (textField == credits) {
		[credits resignFirstResponder];
	//}
	//else if (textField == semester) {
		[semester resignFirstResponder];
	//}
	
	
	return YES;
} //textFieldShouldReturn
-(IBAction) Hidekb {
	//if (textField == cgpa) {
	[cgpa resignFirstResponder];
	//}
	//else if (textField == credits) {
	[credits resignFirstResponder];
	//}
	//else if (textField == semester) {
	[semester resignFirstResponder];
	//}
}	



@end

